package com.shiva.oms;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import com.sf.shiva.oms.common.exception.InitializationException;
import com.shiva.oms.logview.domain.LogData;
import com.shiva.oms.logview.domain.ParsingContext;
import com.shiva.oms.logview.domain.RenamedLevel;
import com.shiva.oms.server.parser.Log4jPatternMultilineLogParser;

//import pl.otros.logview.RenamedLevel;
//import pl.otros.logview.api.InitializationException;
//import pl.otros.logview.api.importer.LogImporterUsingParser;
//import pl.otros.logview.api.model.LogData;
//import pl.otros.logview.api.model.LogDataCollector;
//import pl.otros.logview.api.parser.ParsingContext;
//import pl.otros.logview.api.store.MemoryLogDataStore;
//import pl.otros.logview.parser.log4j.Log4jPatternMultilineLogParser;

/**
 * 
 * 
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2018年3月15日         LA.01367604           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author LA.01367604
 * @version 1.0
 */
public class Exemple {

    private static String propertyFileName = "/resources/config.properties";
    private static final String LEVEL_ATTR = "level";

    public static void main(String[] args) {
        // File logfile = new
        // File("C:\\Users\\la.01367604\\Desktop\\日志\\CX微服务\\error.log");
        // String line = null;
//        try {
        // InputStream in = new FileInputStream(logfile);
        // BufferedReader logReader = new BufferedReader(new
        // InputStreamReader(in));
        // line = logReader.readLine().trim();
        // line = line.replace('\u0000', ' ').replace("  ", " ");
        // } catch (FileNotFoundException e) {
//            // TODO 自动生成的 catch 块
//            e.printStackTrace();
        // } catch (IOException e) {
//            // TODO 自动生成的 catch 块
//            e.printStackTrace();
//        }

        // String line =
        // "2018-03-14 09:26:14 ERROR 10.202.41.26 consumer-task-SGSIF_APPOINTMENT_MESSAGE_SUBSCRIBE_OMS-15 MS  com.sf.shiva.oms.appointment.updatestate.eventhandle.ConsignSuccessTaskHandleBiz saveWaybillNoToOrderNo saveWaybillNoToOrderNo error! orderNo:02799022714283505719890674, waybillNo:608009524537, could not execute batch; SQL [insert into tt_waybill_no_to_order_no (waybill_no, order_no, create_time, id) values (?, ?, ?, ?)]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute batch";
        // //String line =
        // "2018-03-14 09:26:14 ERROR 10.202.41.26 consumer-task-SGSIF_APPOINTMENT_MESSAGE_SUBSCRIBE_OMS-15 MS";
        // String regexStr =
        // "(\\S+-\\S+-\\S+ \\S+:\\S+:\\S+)[ ]+(\\s*?\\S*\\s*?)[ ]+(.*?)[ ]+(.*?)[ ]+(.*?)[ ]+(.*?)[ ]+(.*?)[ ]+(.*?)";
        // // String regexStr =
        // "(\\S+-\\S+-\\S+ \\S+:\\S+:\\S+)[ ]+(\\s*?\\S*\\s*?)[ ]+(\\s*?\\S*\\s*?)[ ]+(\\s*?\\S*\\s*?)[ ]+(\\s*?\\S*\\s*?)[ ]+(\\s*?\\S*\\s*?)[ ]+(\\s*?\\S*\\s*?)[ ]+(.*?)";
        // Pattern regexpPattern = Pattern.compile(regexStr);//
        // "(\\S+-\\S+-\\S+ \\S+:\\S+:\\S+)[ ]+"
//
        // Matcher eventMatcher = regexpPattern.matcher(line);
        // if (eventMatcher.matches()) {
        // System.out.println("有数据:" + eventMatcher.groupCount());
        // MatchResult result = eventMatcher.toMatchResult();
        // for (int i = 1; i < result.groupCount() + 1; i++) {
        // System.out.println(eventMatcher.group(i));
        // }
        // } else {
        // System.out.println("no");
        // }

//        try {
//            File logfile1 = new File(
//                    "C:\\Users\\la.01367604\\Desktop\\日志\\CX微服务\\error.log.2018-03-12\\error.log.2018-03-12");
//            InputStream in = new FileInputStream(logfile1);
//            Properties properties = new Properties(); // 配置文件
//            properties.load(Exemple.class.getResourceAsStream(propertyFileName));
//            // properties.setProperty("dateFormat", "yyyy-MM-dd HH:mm:ss");
//            ParsingContext parsingContext = new ParsingContext("123", "test");
//
//            Log4jPatternMultilineLogParser log4jParser = new Log4jPatternMultilineLogParser();
//            LogDataCollector coll = new MemoryLogDataStore();
//            LogImporterUsingParser logParser = new LogImporterUsingParser(log4jParser);
//
//            logParser.init(properties);
//            logParser.initParsingContext(parsingContext);
//            logParser.importLogs(in, coll, parsingContext);
//
//            List<LogData> showDatas = coll.getLogDataList();
//            System.out.println("共 " + showDatas.size() + "条");
//            showDatas.stream().forEach(data -> System.out.println(createPrintData(data)));
//
//            // 按已知类别过滤日志数据
//            showDatas = showDatas.parallelStream()
//                    .filter(data -> RenamedLevel.ERROR.equals(data.getLevel()))
//                    .collect(Collectors.toList());
//
//            Map<String, String> filterCon = new HashMap<>();
//            filterCon.put("level", "error");
//
//            // 将日志数据分组
//            showDatas
//                    .stream()
//                    .filter(data -> isFilterByCond(filterCon, data))
//                    .collect(Collectors.groupingBy(LogData::getCategory, Collectors.toList()))
//                    .forEach(
//                        (name, datasByName) -> {
//                            datasByName.stream().forEach(
//                                data -> {
//                                    String className = data.getClazz();
//                                    String caName = className.substring(
//                                        className.lastIndexOf('.') + 1, className.length())
//                                            + ":"
//                                            + data.getMethod();
//                                    data.getCategoryNames().add(caName);
//                                    // data.getCategoryIds().add(String.valueOf(list.size()
//                                    // + 1));
//                                });
//                        });
//
//            // System.out.println(JsonUtil.object2Json(showDatas));
//            showDatas.stream().forEach(data -> System.out.println(data.getCategoryName()));
//        } catch (IOException e) {
//            // TODO 自动生成的 catch 块
//            e.printStackTrace();
//        } catch (InitializationException e) {
//            // TODO 自动生成的 catch 块
//            e.printStackTrace();
//        }
    }

//    private static boolean isFilterByCond(Map<String, String> filterCon, LogData data) {
//        for (Map.Entry<String, String> entry : filterCon.entrySet()) {
//            if (LEVEL_ATTR.equals(entry.getKey())) { // 日志级别进行筛选
//                return entry.getValue().toUpperCase().equals(data.getLevel().toString());
//            }
//        }
//        return false;
//    }
//
//    private static final String printFormat = "LogData-%d：【dataTime】=%s, 【level】=%s, 【thread】=%s, 【ndc】=%s, 【line】=%s, 【loggerName】=%s, 【note】=%s, 【clazz】=%s, 【method】=%s, 【message】=%s";
//    private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//    private static String createPrintData(LogData data) {
//        return String.format(printFormat, data.getId(), dateTimeFormat.format(data.getDate()),
//            data.getLevel(), data.getThread(), data.getNDC(), data.getLine(), data.getLoggerName(),
//            data.getNote(), data.getClazz(), data.getMethod(), data.getMessage());
//    }

    // public List<LogDataCluster> regroup(File file, Map<String, String>
    // filterCon) {
    // List<LogDataCluster> dataClusterList = new ArrayList<>();
    // try {
    // InputStream inputData = new FileInputStream(file);
    // List<LogData> list = parse(inputData);
    // if (filterCon!=null && filterCon.size()>0){
    // list= list.stream()
    // .filter(data -> isFilterByCond(filterCon,
    // data)).collect(Collectors.toList());
//            }
    // list.stream()
    // .collect(Collectors.groupingBy(LogData::getCategory,
    // Collectors.toList()))
    // .forEach((name, datasByName) -> {
    // LogDataCluster clu = new LogDataCluster();
    // String className= datasByName.get(0).getClazz();
    // clu.setCategoryName(className.substring(className.lastIndexOf('.') + 1,
    // className.length()) +":"+datasByName.get(0).getMethod());
    // clu.getLogDataList().addAll(datasByName);
    // clu.setCategoryId(String.valueOf(dataClusterList.size() + 1));
    // dataClusterList.add(clu);
    // });
    // } catch (Exception e) {
    // logger.error("logviewer parse error! " + e);
//        }
    // return dataClusterList;
//    }
}
